<template>
  <el-dialog 
    v-model="visible" 
    :title="isEdit ? '编辑文章' : '写文章'" 
    fullscreen 
    :show-close="false" 
    :modal="false"
    @close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header flex items-center justify-between">
        <h4 class="font-bold">{{ isEdit ? '编辑文章' : '写文章' }}</h4>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            <el-icon class="mr-1">
              <Promotion />
            </el-icon>
            {{ isEdit ? '提交' : '发布' }}
          </el-button>
        </div>
      </div>
    </template>

    <el-form 
      :model="form" 
      ref="formRef" 
      label-position="top" 
      size="large" 
      :rules="rules"
    >
      <el-form-item label="标题" prop="title">
        <el-input 
          v-model="form.title" 
          autocomplete="off" 
          size="large" 
          maxlength="40" 
          show-word-limit 
          clearable 
        />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <MdEditor 
          v-model="form.content" 
          @onUploadImg="onUploadImg" 
          :editorId="isEdit ? 'updateArticleEditor' : 'publishArticleEditor'" 
        />
      </el-form-item>

      <el-form-item label="封面" prop="titleImage">
        <el-card class="upload-card">
          <!-- 单图上传区域 -->
          <div class="single-image-upload">
            <div 
              v-if="!form.titleImage"
              @click="openImageDialog"
              class="upload-placeholder"
            >
              <div class="upload-content">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div>点击选择封面</div>
              </div>
            </div>
            
            <!-- 图片预览 -->
            <div v-if="form.titleImage" class="image-preview">
              <img :src="form.titleImage" class="preview-img" />
              <div class="image-actions">
                <el-button type="danger" circle size="small" @click="clearImage">
                  <el-icon><Delete /></el-icon>
                </el-button>
                <el-button type="primary" circle size="small" @click="previewImage">
                  <el-icon><View /></el-icon>
                </el-button>
                <el-button type="info" circle size="small" @click="openImageDialog">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-form-item>

      <el-form-item label="摘要" prop="description">
        <el-input 
          v-model="form.description" 
          :rows="3" 
          type="textarea" 
          placeholder="请输入文章摘要" 
        />
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <el-select 
          v-model="form.categoryId" 
          clearable 
          placeholder="---请选择---" 
          size="large"
          class="w-full"
        >
          <el-option 
            v-for="item in categories" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" 
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标签" prop="tags">
        <el-select 
          v-model="form.tags" 
          multiple 
          filterable 
          remote 
          reserve-keyword 
          placeholder="---请输入---"
          remote-show-suffix 
          :remote-method="remoteMethod" 
          allow-create 
          default-first-option
          :loading="tagSelectLoading" 
          size="large"
          class="w-full"
        >
          <el-option 
            v-for="item in options" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" 
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 素材选择对话框 -->
    <el-dialog 
      v-model="imageDialogVisible" 
      title="选择封面图片" 
      width="1000px" 
      destroy-on-close
    >
      <ImageManage @selectImage="selectImage" />
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[form.titleImage]"
      :initial-index="0"
      @close="previewVisible = false"
    />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { Plus, Delete, View, Edit, Promotion } from '@element-plus/icons-vue'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { showMessage } from '@/composables/util'
import { uploadFile } from '@/api/admin/file'
import { getCategorySelect } from '@/api/admin/category'
import { selectTags, getTagSelect } from '@/api/admin/tag'
import { publishArticle, updateArticle, getArticleDetail } from '@/service/api/blog/classificationman'
import ImageManage from "@/views/function/material/Image/index.vue"

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  articleData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const imageDialogVisible = ref(false)
const previewVisible = ref(false)
const tagSelectLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  title: '',
  content: '请输入内容',
  titleImage: '',
  categoryId: null,
  tags: [],
  description: ""
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 40, message: '文章标题要求大于1个字符，小于40个字符', trigger: 'blur' },
  ],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  titleImage: [{ required: true, message: '请选择封面图片', trigger: 'change' }],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  tags: [{ required: true, message: '请选择文章标签', trigger: 'blur' }],
  description: [{ required: true, message: '请输入文章摘要', trigger: 'blur' }],
}

// 分类和标签数据
const categories = ref([])
const options = ref([])

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    initDialog()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 初始化对话框
const initDialog = async () => {
  if (props.articleData) {
    isEdit.value = true
    await loadArticleDetail(props.articleData.id)
  } else {
    isEdit.value = false
    resetForm()
  }
  
  // 加载分类和标签数据
  await loadCategories()
  await loadTags()
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.title = ''
  form.content = '请输入内容'
  form.titleImage = ''
  form.categoryId = null
  form.tags = []
  form.description = ''
}

// 加载文章详情
const loadArticleDetail = async (articleId) => {
  try {
    const res = await getArticleDetail(articleId)
    if (res.success) {
      form.id = res.data.id
      form.title = res.data.title
      form.content = res.data.content
      form.titleImage = res.data.titleImage
      form.categoryId = res.data.categoryId
      form.tags = res.data.tagIds
      form.description = res.data.description
    }
  } catch (error) {
    console.error('加载文章详情失败:', error)
    showMessage('加载文章详情失败', 'error')
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await getCategorySelect()
    categories.value = res.data || []
  } catch (error) {
    console.error('加载分类数据失败:', error)
  }
}

// 加载标签数据
const loadTags = async () => {
  try {
    const res = await getTagSelect()
    options.value = res.data || []
  } catch (error) {
    console.error('加载标签数据失败:', error)
  }
}

// 远程搜索标签
const remoteMethod = (query) => {
  if (query) {
    tagSelectLoading.value = true
    setTimeout(() => {
      tagSelectLoading.value = false
      selectTags(query).then((res) => {
        if (res.success) {
          options.value = res.data
        }
      })
    }, 200)
  }
}

// 打开图片选择对话框
const openImageDialog = () => {
  imageDialogVisible.value = true
}

// 选择图片
const selectImage = (url) => {
  form.titleImage = url
  imageDialogVisible.value = false
  showMessage('封面图片选择成功', 'success')
}

// 清除图片
const clearImage = () => {
  form.titleImage = ''
}

// 预览图片
const previewImage = () => {
  if (form.titleImage) {
    previewVisible.value = true
  }
}

// MD编辑器图片上传
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((resolve, reject) => {
        console.log('==> 开始上传文件...')
        let formData = new FormData()
        formData.append("file", file)
        uploadFile(formData).then((res) => {
          console.log('访问路径：' + res.data.url)
          callback([res.data.url])
          resolve(res.data.url)
        }).catch(reject)
      })
    })
  )
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      return false
    }

    try {
      let res
      if (isEdit.value) {
        res = await updateArticle(form)
      } else {
        res = await publishArticle(form)
      }

      if (res.success === false) {
        showMessage(res.message, 'warning')
        return
      }

      showMessage(isEdit.value ? '修改成功' : '发布成功', 'success')
      handleClose()
      emit('success')
    } catch (error) {
      console.error('提交失败:', error)
      showMessage('提交失败', 'error')
    }
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}
</script>

<style scoped>
.upload-card {
  border: none;
  box-shadow: none;
}

.single-image-upload {
  width: 200px;
  height: 120px;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  cursor: pointer;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.2s;
}

.upload-placeholder:hover {
  border-color: var(--el-color-primary);
}

.upload-content {
  text-align: center;
  color: #909399;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

.w-full {
  width: 100%;
}

.my-header {
  padding: 0 20px;
}
</style> 